var jxAppMS = angular.module('JxApp.mulsel', ['ngSanitize', 'services']);

function stopKeyEvent(keyEvent) {
	if (!keyEvent) var keyEvent = window.event;
	
	//e.cancelBubble is supported by IE -
	// this will kill the bubbling process.
	keyEvent.cancelBubble = true;
	keyEvent.returnValue = false;
	
	//e.stopPropagation works only in Firefox.
	if (keyEvent.stopPropagation) keyEvent.stopPropagation();
	if (keyEvent.preventDefault) keyEvent.preventDefault();
	return false;
}

/**
 * 过滤器，实现高亮
 */
jxAppMS.filter('highlight', function () {
	return function (input, keyWord) {
		if (input == undefined) {
			return input;
		}
		var reg = new RegExp('(' + keyWord + ')', 'i');//i表示匹配不敏感大小写
		var highlightWord = input.replace(reg, "<span class='highlight'>" + "$1" + "</span>");
		return highlightWord;
		
	};
});

jxAppMS.directive('mulselect', function (httpServices) {
	return {
		restrict: 'AE',
		//template: '<div>Hi there</div>',
		templateUrl: getContextPath() + '/template/nadmin/js/jx/multiselect.html',
		// templateUrl:'../js/jx/multiselect.html',
		// replace: true,
		transclude: true,
		scope: {
			name: '@',
			url: '@',
			'class': '@',
			initvalue: '=initvalue',
			datareader: '@',
			iid: '@',
			placeholder: '@',
			onselectchange: '@',
			searchplaceholder: '@',
			onselected: '@',
			MsModel: '=ngModel',
			selVal: '=',
			localData: '=data',
			mulselectReadonly: '=readonly',
			disabled: '=disabled',
			exoptions: '@',
			addtip: '@',
			loadData: '=?loadData',
			addurl: '@',
			showAddUrl: '@',
			showRefreshBtn: '@'
		},
		link: function (scope, iElement, iAttrs) {
			if (iAttrs.datareader === undefined) {
				var dataReaderJson = "";
			} else {
				eval("var dataReaderJson = " + iAttrs.datareader);
			}
			scope.init(dataReaderJson, iAttrs.url);
			//当前查询输入框
			scope.curSearchInput = $(iAttrs.$$element).find("input[ng-model='searchKey']")[0];
			scope.$watch('mulselectReadonly', function (value) {
				if (scope.mulselectReadonly) {
					iElement.addClass("mulsel-readonly");
				} else {
					iElement.removeClass("mulsel-readonly");
				}
				
			});
			
			scope.$watch('exoptions', function (value) {
				scope.exoptions = value;
				scope.setListData(scope.msData);
			});
		},
		controller: function ($scope, $filter, httpServices) {
			
			/**
			 * 初始化
			 * @param data
			 * @param initvalue
			 */
			$scope.init = function (dataReader, url) {
				$scope.loadingOptions = false;
				$scope.nullOptions = true;
				$scope.loadingPage = false;
				
				if ($scope.MsModel == undefined) {
					$scope.MsModel = {};
				}
				$scope.dataReader = dataReader;
				$scope.url = url;
				var params = {page: 1};
				$scope.reloadData({}, params);
				
			};
			
			/**
			 * 重载数据
			 * @param data
			 */
			$scope.reloadData = function (postData, paramsJson) {
				$scope.setListData();
				$scope.loadingOptions = true;
				
				httpServices.get($scope.url, {
					params: paramsJson, headers: {
						'Content-Type': 'application/x-www-form-urlencoded', charset: 'utf-8'
					}
				}).success(function (data) {
					$scope.loadingOptions = false;
					$scope.loadData = angular.copy(data);
					$scope.setListData(data);
				});
				
			};
			
			/**
			 * 设置下拉列表数据
			 */
			$scope.setListData = function (data) {
				//初始化选中的列表项序号
				$scope.optionAct = -1;
				$scope.nullOptions = true;
				
				if (data == undefined || data == '') {
					$scope.options = undefined;
					return;
				}
				
				$scope.msData = data;
				$scope.options = transKeyMap($scope.msData.optionList, $scope.dataReader);
				if ($scope.exoptions) {
					if ($scope.options.length == 0 && $scope.searchKey && $scope.searchKey != '') {
						// 有关键字并且返回的结果为空
						eval("var exoptions = " + $scope.exoptions);
						exoptions = $filter('filter')(exoptions, {text: $scope.searchKey});
						// 如果额外的选项也没有匹配项，则显示所有额外的选项
						if (exoptions.length == 0) {
							eval("exoptions = " + $scope.exoptions);
						}
						for (var i = (exoptions.length - 1); i >= 0; i--) {
							$scope.options.unshift(exoptions[i]);
						}
					} else if ($scope.options.length != 1
						|| $scope.searchKey == undefined || $scope.searchKey == null || $scope.searchKey == '') {
						eval("var exoptions = " + $scope.exoptions);
						for (var i = (exoptions.length - 1); i >= 0; i--) {
							$scope.options.unshift(exoptions[i]);
						}
					}
				}
				
				$scope.pageInfo = $scope.msData.currentPage + "/" + $scope.msData.totalPage;
				
				if ($scope.msData.currentPage <= 1) {
					$scope.preBtn = "disableBtn";
				} else {
					$scope.preBtn = "pointer";
				}
				
				if ($scope.msData.currentPage >= $scope.msData.totalPage) {
					$scope.nextBtn = "disableBtn";
				} else {
					$scope.nextBtn = "pointer";
				}
				
				if ($scope.options.length > 0) {
					$scope.nullOptions = false;
				}
			};
			
			/**
			 * 点击选项
			 * @param opition
			 */
			$scope.selected = function (option) {
				var selValChange = false;
				if ($scope.selVal != option.val) {
					selValChange = true;
				}
				
				$scope.selVal = option.val;
				$scope.MsModel = option;
				
				if (selValChange && $scope.onselectchange) {
					var onselectchangeFun = $scope.onselectchange.substring(0, $scope.onselectchange.indexOf('('));
					if (typeof ($scope.$parent[onselectchangeFun]) == 'function') {
						eval("setTimeout(function(){$scope.$parent." + $scope.onselectchange + "});");
					}
				}
				
				if ($scope.onselected) {
					var onselectedFun = $scope.onselected.substring(0, $scope.onselected.indexOf('('));
					if (typeof ($scope.$parent[onselectedFun]) == 'function') {
						eval("setTimeout(function(){$scope.$parent." + $scope.onselectedFun + "('" + $scope.MsModel.val + "','" + $scope.MsModel.text + "')" + "});");
					}
				}
				
				//清空查询条件
				$scope.searchKey = '';
				var params = {page: 1};
				$scope.reloadData({}, params);
				
				setTimeout(function () {
					$scope.$apply(function (scope) {
						scope.optionShow = false;
					});
				});
			};
			
			/**
			 * 失焦点事件
			 * @param opition
			 */
			$scope.textBlur = function (opition) {
			};
			
			/**
			 * 查询输入框失焦点事件
			 * @param opition
			 */
			$scope.searchInputBlur = function () {
//            	if($scope.optionShow){
//            		$scope.curSearchInput.focus();
//            	}
			};
			
			/**
			 * 下一页
			 */
			$scope.nextPage = function () {
				if ($scope.msData.currentPage >= $scope.msData.totalPage) {
					/*$scope.clickIn();*/
					return;
				} else {
					var paramsJson = {page: $scope.msData.currentPage + 1, searchKey: $scope.searchKey};
					$scope.loadingPage = true;
					$scope.loadingOptions = true;
					$scope.setListData();
					httpServices.get($scope.url, {
						params: paramsJson, headers: {
							'Content-Type': 'application/x-www-form-urlencoded', charset: 'utf-8'
						}
					}).success(function (data) {
						$scope.loadingOptions = false;
						$scope.loadingPage = false;
						$scope.setListData(data);
					});
				}
			};
			
			/**
			 * 上一页
			 */
			$scope.prePage = function () {
				
				if ($scope.msData.currentPage <= 1) {
					/* $scope.clickIn();*/
					return;
				} else {
					var paramsJson = {page: $scope.msData.currentPage - 1, searchKey: $scope.searchKey};
					$scope.loadingPage = true;
					$scope.loadingOptions = true;
					$scope.setListData();
					httpServices.get($scope.url, {
						params: paramsJson, headers: {
							'Content-Type': 'application/x-www-form-urlencoded', charset: 'utf-8'
						}
					}).success(function (data) {
						$scope.loadingOptions = false;
						$scope.loadingPage = false;
						$scope.setListData(data);
					});
					
				}
			};
			
			/**
			 * 输入事件
			 */
			$scope.change = function () {
				/*$scope.selVal =  '';
				$scope.MsModel.val = '';*/
				var params = {page: 1, searchKey: $scope.searchKey};
				$scope.reloadData({}, params);
			};
			/**
			 * 点击输入框事件
			 */
			$scope.clickIn = function () {
				if ($scope.mulselectReadonly || $scope.disabled) //如果是只读或者禁用的
				{
					return;
				}
				$scope.optionAct = -1;//初始化选中的列表项序号
				$scope.optionShow = !$scope.optionShow;
				setTimeout(function () {
					$scope.curSearchInput.focus();
				});
			};
			
			/**
			 * 点击查询输入框
			 */
			$scope.clickSearchInput = function (e) {
				stopKeyEvent(e); //点击查询输入框阻止触发关闭下拉列表事件
			};
			
			/*光标移开事件*/
			$scope.mouseleave = function () {
				if ($scope.loadingPage) {
					$scope.optionShow = true;
				} else {
					$scope.optionShow = false;
				}
			};
			
			/**
			 * 查询输入框中按下键盘事件
			 */
			$scope.searchPress = function (keyEvent) {
				var keyCode = keyEvent.which;
				
				switch (keyCode) {
					
					case 38: //up
						$scope.searchCtrlUp(keyEvent);
						break;
					case 40: //down
						$scope.searchCtrlDown(keyEvent);
						break;
					case 13: //Enter
						$scope.searchCtrlEnter(keyEvent);
						break;
					case 33: //PageUp
						$scope.searchCtrlPageup(keyEvent);
						break;
					case 34: //PageDown
						$scope.searchCtrlPagedown(keyEvent);
						break;
					default:
					
				}
				
			};
			
			/**
			 * 查询输入框中按下键盘事件,向上键
			 */
			$scope.searchCtrlUp = function (keyEvent) {
				if ($scope.optionAct > 0) {
					$scope.optionAct--;
				}
				stopKeyEvent(keyEvent);
			};
			/**
			 * 查询输入框中按下键盘事件,向下键
			 */
			$scope.searchCtrlDown = function (keyEvent) {
				if ($scope.optionAct < $scope.options.length - 1) {
					$scope.optionAct++;
				}
				stopKeyEvent(keyEvent);
			};
			/**
			 * 查询输入框中按下键盘事件,Enter键
			 */
			$scope.searchCtrlEnter = function (keyEvent) {
				if ($scope.options.length == 1) {
					$scope.selected($scope.options[0]);
					$scope.optionAct = -1;
				}
				if ($scope.optionAct > -1 && $scope.optionAct < $scope.options.length) {
					$scope.selected($scope.options[$scope.optionAct]);
					$scope.optionAct = -1;//处理完后初始化为-1
				}
				stopKeyEvent(keyEvent);
			};
			/**
			 * 查询输入框中按下键盘事件,PageUp键
			 */
			$scope.searchCtrlPageup = function (keyEvent) {
				$scope.prePage();
				stopKeyEvent(keyEvent);
			};
			/**
			 * 查询输入框中按下键盘事件,PageDown键
			 */
			$scope.searchCtrlPagedown = function (keyEvent) {
				$scope.nextPage();
				stopKeyEvent(keyEvent);
			};
			
			/**
			 * html转义
			 */
			$scope.htmlEncode = function (val) {
				return htmlEncode(val);
			};
		}
	};
});


/**************************************************
 * 步长组件
 **************************************************/
jxAppMS.directive('rnStepper', function ($compile) {
	return {
		restrict: 'AE',
		transclude: true,
		controller: function ($scope, httpServices) {
			
			$scope.ngModel = 0;
			
			$scope.options = {};
			
			
			$scope.decrement = function () {
				if ($scope.ngModel == "" || $scope.ngModel == undefined) {
					$scope.ngModel = $scope.options.min;
				}
				var newValue = parseFloat(accSub($scope.ngModel, $scope.options.stepper));
				if ($scope.options.min >= newValue) {
					newValue = $scope.options.min;
				}
				
				$scope.ngModel = newValue;
			};
			$scope.increment = function () {
				if ($scope.ngModel == "" || $scope.ngModel == undefined) {
					$scope.ngModel = $scope.options.min;
				}
				var newValue = accAdd($scope.ngModel, $scope.options.stepper);
				if ($scope.options.max <= newValue) {
					newValue = $scope.options.max;
				}
				$scope.ngModel = newValue;
			};
		},
		scope: {
			ngModel: '=',
		},
		link: function (scope, iElement, iAttrs) {
			var before = $compile('<a class="st_a st_minus" href="javascript:;" ng-click="decrement()">-</a>')(scope);
			var after = $compile('<a class="st_a st_add" href="javascript:;" ng-click="increment()">+</a>')(scope);
			var inputOjb = angular.element(iElement[0]);
			// inputOjb.after( );
			jQuery(inputOjb).before(before);
			jQuery(inputOjb).after(after);
			
			
			if (iAttrs.options === undefined) {
				var optionsJson = {};
			} else {
				eval("var optionsJson = " + iAttrs.options);
			}
			
			if (optionsJson.initvalue != undefined) {
				scope.ngModel = optionsJson.initvalue;
			}
			scope.options = optionsJson;
			
			if (scope.options.stepper == undefined) {
				scope.options.stepper = 1;
			}
		}
	};
});


/**************************************************
 * 自定义选择框组件
 **************************************************/
jxAppMS.directive('exselect', function () {
	return {
		restrict: 'AE',
		templateUrl: getContextPath() + '/template/nadmin/js/jx/extendselect.html',
		transclude: true,
		scope: {
			name: '@',
			url: '@',
			'class': '@',
			initvalue: '=initvalue',
			datareader: '@',
			iid: '@',
			placeholder: '@',
			searchplaceholder: '@',
			onselectchange: '@',
			onselected: '@',
			selVal: '=',
			MsModel: '=ngModel',
			data: '=data',
			mulselectReadonly: '=readonly',
			disabled: '=disabled',
			exoptions: '@',
			addtip: '@',
			addurl: '@'
		},
		link: function (scope, iElement, iAttrs) {
			if (iAttrs.datareader === undefined) {
				var dataReaderJson = "";
			} else {
				eval("var dataReaderJson = " + iAttrs.datareader);
			}
			
			scope.init(dataReaderJson);
			
			scope.curSearchInput = $(iAttrs.$$element).find("input[ng-model='searchKey']")[0]; //当前查询输入框
			
			scope.$watch('mulselectReadonly', function (value) {
				if (scope.mulselectReadonly) {
					iElement.addClass("mulsel-readonly");
				} else {
					iElement.removeClass("mulsel-readonly");
				}
				
			});
			scope.$watch('data', function (value) {
				scope.searchKey = '';
				scope.setListData();
			});
			scope.$watch('selVal', function (value) {
				
				if (scope.selVal != undefined) {
					var option = getObject(scope.options, 'val', scope.selVal);
					if (option) {
						scope.MsModel = option;
					}
				} else {
					scope.MsModel = {};
				}
			});
		},
		controller: function ($scope, $filter) {
			
			/**
			 * 初始化
			 * @param data
			 * @param initvalue
			 */
			$scope.init = function (dataReader) {
				$scope.nullOptions = true;
				
				if ($scope.MsModel == undefined) {
					$scope.MsModel = {};
				}
				$scope.dataReader = dataReader;
				$scope.setListData();
				
			};
			
			
			/**
			 * 设置下拉列表数据
			 */
			$scope.setListData = function (searchKey) {
				$scope.optionAct = -1;//初始化选中的列表项序号
				$scope.nullOptions = true;
				
				if ($scope.data == undefined || $scope.data == '') {
					$scope.options = undefined;
					return;
				}
				
				$scope.options = angular.copy($scope.data);
				transKeyMap($scope.options, $scope.dataReader);
				
				if ($scope.exoptions) {
					if ($scope.options.length == 0 && $scope.searchKey && $scope.searchKey != '') {
						// 有关键字并且返回的结果为空
						eval("var exoptions = " + $scope.exoptions);
						exoptions = $filter('filter')(exoptions, {text: searchKey});
						// 如果额外的选项也没有匹配项，则显示所有额外的选项
						if (exoptions.length == 0) {
							eval("exoptions = " + $scope.exoptions);
						}
						for (var i = (exoptions.length - 1); i >= 0; i--) {
							$scope.options.unshift(exoptions[i]);
						}
						;
					} else if ($scope.options.length != 1
						|| $scope.searchKey == undefined || $scope.searchKey == null || $scope.searchKey == '') {
						eval("var exoptions = " + $scope.exoptions);
						for (var i = (exoptions.length - 1); i >= 0; i--) {
							if (!getObject($scope.options, 'val', exoptions[i].val)) {
								$scope.options.unshift(exoptions[i]);
							}
						}
						;
					}
				}
				
				
				$scope.options = $filter("filter")($scope.options, {text: searchKey});
				
				if ($scope.options.length > 0) {
					$scope.nullOptions = false;
				}
				
				//如果当前已经设置了选中值则进行设置
				if ($scope.selVal != undefined) {
					var option = getObject($scope.options, 'val', $scope.selVal);
					if (option) {
						$scope.MsModel = option;
					}
				} else {
					$scope.MsModel = {};
				}
			};
			
			/**
			 * 点击选项
			 * @param opition
			 */
			$scope.selected = function (option) {
				var selValChange = false;
				if ($scope.selVal != option.val) {
					selValChange = true;
				}
				
				$scope.selVal = option.val;
				$scope.MsModel = option;
				
				if (selValChange && $scope.onselectchange) {
					var onselectchangeFun = $scope.onselectchange.substring(0, $scope.onselectchange.indexOf('('));
					if (typeof ($scope.$parent[onselectchangeFun]) == 'function') {
						eval("setTimeout(function(){$scope.$parent." + $scope.onselectchange + "});");
					}
				}
				
				//清空查询条件
				$scope.searchKey = '';
				$scope.setListData();
				
				setTimeout(function () {
					$scope.$apply(function (scope) {
						scope.optionShow = false;
					});
				});
				
				if ($scope.onselected && $.trim($scope.onselected) != "") {
					eval($scope.onselected + "('" + $scope.MsModel.val + "','" + $scope.MsModel.text + "')");
				}
				
			};
			
			
			/**
			 * 输入事件
			 */
			$scope.change = function () {
				$scope.setListData($scope.searchKey);
			};
			/**
			 * 点击输入框事件
			 */
			$scope.clickIn = function () {
				if ($scope.mulselectReadonly || $scope.disabled) //如果是只读或者禁用的
				{
					return;
				}
				
				$scope.optionAct = -1;//初始化选中的列表项序号
				$scope.optionShow = !$scope.optionShow;
				setTimeout(function () {
					$scope.curSearchInput.focus();
				});
			};
			
			/**
			 * 点击查询输入框
			 */
			$scope.clickSearchInput = function (e) {
				stopKeyEvent(e); //点击查询输入框阻止触发关闭下拉列表事件
			};
			
			/*光标移开事件*/
			$scope.mouseleave = function () {
				$scope.optionShow = false;
			};
			
			/**
			 * 查询输入框中按下键盘事件
			 */
			$scope.searchPress = function (keyEvent) {
				var keyCode = keyEvent.which;
				
				switch (keyCode) {
					
					case 38: //up
						$scope.searchCtrlUp(keyEvent);
						break;
					case 40: //down
						$scope.searchCtrlDown(keyEvent);
						break;
					case 13: //Enter
						$scope.searchCtrlEnter(keyEvent);
						break;
					default:
					
				}
				
			};
			
			/**
			 * 查询输入框中按下键盘事件,向上键
			 */
			$scope.searchCtrlUp = function (keyEvent) {
				if ($scope.optionAct > 0) {
					$scope.optionAct--;
				}
				stopKeyEvent(keyEvent);
			};
			/**
			 * 查询输入框中按下键盘事件,向下键
			 */
			$scope.searchCtrlDown = function (keyEvent) {
				if ($scope.optionAct < $scope.options.length - 1) {
					$scope.optionAct++;
				}
				stopKeyEvent(keyEvent);
			};
			/**
			 * 查询输入框中按下键盘事件,Enter键
			 */
			$scope.searchCtrlEnter = function (keyEvent) {
				if ($scope.options.length == 1) {
					$scope.selected($scope.options[0]);
					$scope.optionAct = -1;
				}
				if ($scope.optionAct > -1 && $scope.optionAct < $scope.options.length) {
					$scope.selected($scope.options[$scope.optionAct]);
					$scope.optionAct = -1;//处理完后初始化为-1
				}
				stopKeyEvent(keyEvent);
			};
		}
	};
});